package com.shu.auth.utils;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.shu.auth.exception.ParamException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

/**
 * bean校验
 */
@Slf4j
public class BeanValidator {
    //全局校验
    private static ValidatorFactory validatorFactory= Validation.buildDefaultValidatorFactory();

    /**
     * 校验bean
     * @param t
     * @param groups
     * @param <T>
     * @return
     */
    public static <T> Map<String,String> validate(T t,Class... groups){
        //工厂里面获得Validator
        Validator validator = validatorFactory.getValidator();
        //校验并返回
        Set<ConstraintViolation<T>> validateResult = validator.validate(t, groups);
        //判断是否为空
        if (validateResult.isEmpty()){
            //返回空的map
            return Collections.emptyMap();
        }else {
            //创建链表map
            LinkedHashMap errors= Maps.newLinkedHashMap();
            //循环校验结果
            Iterator iterator =validateResult.iterator();
            while (iterator.hasNext()){
                ConstraintViolation violation = (ConstraintViolation)iterator.next();
                //把bean属性以及错误信息放入map中并返回
                errors.put(violation.getPropertyPath().toString(),violation.getMessage());
            }
            return errors;
        }


    }

    public static  Map<String,String> validateList(Collection<?> collection){
        //校验是否为空
        Preconditions.checkNotNull(collection);
        Iterator iterator = collection.iterator();
        Map errors=null;
        do {
            //判断是否为空
            if (!iterator.hasNext()){
                return Collections.emptyMap();
            }
            Object object=iterator.next();
            //调用单个校验的方法
            errors=validate(object,new Class[0]);
        //判断errors是否为空
        }while (errors.isEmpty());

        return errors;
    }

    public static Map<String,String> validateObject(Object first,Object... objects){
        if (objects!=null && objects.length>0){
            return validateList(Lists.asList(first,objects));
        }else if (objects!=null){
            return validate(first,new Class[0]);
        }else {
            return Collections.emptyMap();
        }
    }


    public static void check(Object param)throws ParamException{
        Map<String, String> map = BeanValidator.validateObject(param);
        //如果map不为空跑出异常
        if (MapUtils.isNotEmpty(map)){
            log.error(map.toString());
            throw new ParamException(map.toString());
        }

    }
}
